<!-- eslint-disable @typescript-eslint/no-use-before-define -->
<!--
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-10 14:13:31
 * @LastEditTime: 2023-09-08 14:25:40
-->
<script lang="ts" setup name="DictionContent">
import { ikTree } from 'iking-utils'
import type { PropType } from 'vue'
import useUserStore from '@g/store/modules/user'
import { dictApi } from '@/MainApp/apis/dict'
const props = defineProps({
  parent: {
    type: Object as PropType<{ name: string; id: string; }>,
    default: () => {
      return { name: '', id: '' }
    }
  }
})
const { lenContent, lenName } = useLength()
const { dialog, t } = useConfig()
const { msgSuccess, msgError, msgBoxWarnAsync } = useMessage()
const userStore = useUserStore()
const formKey = {
  // 父字典项
  parent: '',
  // 父字典项编号
  parentId: '',
  // 所属字典编号
  dictId: '',
  // 字典项名称
  label: '',
  // 字典项值
  value: '',
  // 备注信息
  remark: '',
  // 能否删除
  deletable: true,

  // 字典是否可见 - 暂无此字段
  visible: true,
  // 排序值
  sortOrder: 999
}
const placeholder = {
  label: '请输入字典项名称',
  value: '请输入字典项值',
  remark: '请输入备注信息'
}
const contentRules = {
  label: [{ required: true, message: placeholder.label, trigger: 'blur' }],
  value: [{ required: true, message: placeholder.value, trigger: 'blur' }],
  visible: [{ required: false, message: '', trigger: 'change' }],
  itemDeletable: [{ required: true, message: '', trigger: 'change' }]
}
const contentRef = ref()
const contentForm = ref(formKey)
const contentState = reactive({
  isEditing: false,
  title: '新增字典项',
  visible: false,
  loading: false,
  contentData: []
})
// const title = computed(() => (contentState.isEditing ? '修改字典项' : '新增字典项'))

watch(
  () => props.parent,
  () => {
    getDictionaryContent()
  }
)
// 查询
const getDictionaryContent = async () => {
  contentState.loading = true
  const { msg, success, data } = await dictApi.getDictContentByItem(props.parent?.id)
  if (success)
    contentState.contentData = ikTree.listToTree(data) || []
  else
    msgError(msg)

  contentState.loading = false
}

// 新增
const handAddDictContent = () => {
  contentRef.value?.resetFields()
  contentForm.value = { ...formKey }
  contentState.visible = true
  contentState.title = '新增字典项'
}

// 新增子项
const handAddChild = (row: typeof formKey & { id: string; }) => {
  contentRef.value?.resetFields()
  contentForm.value = {
    ...formKey,
    parent: row.label,
    parentId: row.id
  }
  contentState.title = '新增子项'
  contentState.visible = true
}

// 修改
const handEditRow = (row: typeof formKey) => {
  contentForm.value = { ...row }
  contentState.isEditing = true
  if (!row.parentId)
    contentState.title = '修改字典项'
  else
    contentState.title = '修改子项'

  contentState.visible = true
}
// 删除
const handDelete = (row: typeof formKey & { id: string; }) => {
  msgBoxWarnAsync('删除确认', `确认删除字典项[ ${row.label} ]吗?`, async () => {
    const { msg, success } = await dictApi.deleteDictContent(row.id)
    if (success) {
      msgSuccess(msg)
      await getDictionaryContent()
      await userStore.getAllDiction()
    }
    else { msgError(msg) }
  })
}
// 关闭
const handleClose = () => {
  contentRef.value?.resetFields()
  contentState.visible = false
  contentState.isEditing = false
}
const handChangePre = (row: typeof formKey) => {
  contentState.isEditing = true
  handConfirm(row)
}
// 确认
const handConfirm = async (row: typeof formKey & { id?: string; } | any) => {
  contentRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      contentState.loading = true
      const { msg, success } = contentState.isEditing
        ? await dictApi.updateDictContent(row?.id ? { ...row } : { ...contentForm.value })
        : await dictApi.addDictContent({
          ...contentForm.value,
          dictId: props.parent.id
        })
      if (success) {
        msgSuccess(msg)
        handleClose()
        await getDictionaryContent()
        await userStore.getAllDiction()
      }
      else { msgError(msg) }
      contentState.loading = false
    }
  })
}

const fields = [{
  key: 'label',
  label: '字典项名称',
  show: true
}, {
  key: 'remark',
  label: '备注',
  show: true
}, {
  key: 'preset',
  label: '是否预置',
  show: true,
  align: 'center',
  tableSlot: 'preset'
}, {
  key: '',
  label: '操作',
  show: true,
  width: useOperateWidth(106, 180),
  showOverflowTooltip: false,
  tableSlot: 'operate',
  fixed: 'right'
}]
</script>

<template>
  <IkPageFull
    ref="refItem"
    :fields="fields"
    highlight-current-row
    row-key="id"
    tab-id="item"
    :table-data="contentState.contentData"
    :search="getDictionaryContent"
    :immediate="false"
    :header-title="`[ ${parent?.name} ] - 字典项列表`"
    :serial="false"
  >
    <template #headerRight>
      <IkSvgIcon
        v-role="'ADD-DICT-ITEM'"
        name="iksvg_xinzeng"
        show-bg
        pop
        :size="20"
        title="新增"
        :start-margin="false"
        @click="handAddDictContent"
      />
    </template>
    <template #preset="{ data }">
      <el-switch
        v-model="data.row.preset"
        inline-prompt
        active-text="是"
        inactive-text="否"
        @change="handChangePre(data.row)"
      />
    </template>
    <template #operate="{ data }">
      <IkBtnContent v-if="!data.row.preset" :num="4">
        <IkSvgIcon
          v-role="'ADD-CHILD-DICT-ITEM'"
          name="icon-xinzeng"
          show-bg
          pop
          in-table
          :start-margin="false"
          :title="t('action.addchild')"
          @click="handAddChild(data.row)"
        />
        <IkSvgIcon
          v-role="'UPDATE-DICT-ITEM'"
          name="icon-bianji"
          show-bg
          pop
          in-table
          :title="t('action.modify')"
          @click="handEditRow(data.row)"
        />
        <IkSvgIcon
          v-role="'DELETE-DICT-ITEM'"
          name="icon-shanchu"
          show-bg
          pop
          in-table
          type="danger"
          :title="t('action.delete')"
          @click="handDelete(data.row)"
        />
      </IkBtnContent>
    </template>
  </IkPageFull>
  <!-- 新增、修改 -->
  <el-dialog
    v-model="contentState.visible"
    :title="contentState.title"
    draggable
    :width="dialog.sl"
    :close-on-click-modal="false"
    class="dict-item"
    @closed="handleClose"
  >
    <el-form
      ref="contentRef"
      :model="contentForm"
      :rules="contentRules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="所属字典">
        <el-tooltip
          effect="dark"
          :content="parent.name"
          placement="top-start"
        >
          <el-input
            v-model.trim="parent.name"
            disabled
            :maxlength="lenName"
            show-word-limit
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item v-if="contentForm.parentId" label="父字典项">
        <el-tree-select
          v-model="contentForm.parentId"
          :data="contentState.contentData"
          check-strictly
          node-key="id"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="字典项名称" prop="label">
        <el-input
          v-model.trim="contentForm.label"
          :maxlength="lenName"
          show-word-limit
          :placeholder="placeholder.label"
        />
      </el-form-item>
      <el-form-item label="字典项值" prop="value">
        <el-input
          v-model.trim="contentForm.value"
          :maxlength="lenName"
          show-word-limit
          :placeholder="placeholder.value"
        />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model.trim="contentForm.remark"
          :maxlength="lenContent"
          show-word-limit
          type="textarea"
          :autosize="{ minRows: 4 }"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button
        bg
        text
        @click="handleClose"
      >
        {{ t("action.cancel") }}
      </el-button>
      <el-button type="primary" :loading="contentState.loading" @click="handConfirm">
        {{ t("action.sure") }}
      </el-button>
    </template>
  </el-dialog>
</template>
